﻿using System.Collections.Concurrent;
using System.Reflection;

namespace Basic.EventBus.Attributes;

[AttributeUsage(AttributeTargets.Class)]
public class EventTopicAttribute : Attribute, IEventAttribute
{
    /// <summary>
    /// 主题名
    /// </summary>
    public string Topic { get; set; }

    /// <summary>
    /// 队列名
    /// </summary>
    public string QueueName { get; set; }

    /// <summary>
    /// 消息Key
    /// </summary>
    public string Key { get; set; }

    /// <summary>
    /// 分组名
    /// </summary>
    public string Group { get; set; }

    /// <summary>
    /// 队列持久化
    /// </summary>
    public bool Durable { get; set; } = true;

    public EventTopicAttribute Parse(Type type)
    {
        Topic ??= type.FullName;
        Key ??= type.Name;
        Group ??= type.Name;
        return this;
    }

    #region Static

    private static ConcurrentDictionary<Guid, EventTopicAttribute> AttributeDict = new ConcurrentDictionary<Guid, EventTopicAttribute>(4, 16);

    public static EventTopicAttribute GetCurrentAttribute(Type type)
    {
        if (type == null)
            return null;

        if (AttributeDict.TryGetValue(type.GUID, out EventTopicAttribute attribute))
            return attribute;

        attribute = type.GetCustomAttribute<EventTopicAttribute>();
        if (attribute != null)
            AttributeDict[type.GUID] = attribute.Parse(type);

        return attribute;
    }

    #endregion

}